$(function(){
  // Note Model
  //  title: String
  //  body: String
  //  created_at: Integer
  //  last_update: Integer
  //  id: String
  // ----------------
  window.Note = Backbone.Model.extend({
    EMPTY_TITLE : "無題",
    EMPTY_BODY : "ここのノートを記述",
    
    initialize: function(){
      var now_ = new Date().getTime();

      this.set({
        title: this.EMPTY_TITLE,
        body: this.EMPTY_BODY,
        created_at: now_,
        last_update: now_
      });
    },
    clear: function() {
      this.destroy();
      this.view.remove();
    }
  });

  // Notes Collection
  // ----------------
  window.Notes = Backbone.Collection.extend({
    model: Note,
    localStorage: new Store("notebooks")
  });

  // Notesオブジェクトのインスタンス生成(Modelへのアクセッサ)
  window.notes = new Notes;

  window.NoteView = Backbone.View.extend({
    tagName: "div",
    template: _.template($("#noteTemplate").html()),
    initialize: function(){
      _.bindAll(this, "render");
      this.model.bind("change", this.render);
    },
    render:function(){
      $(this.el).html(this.template(this.model.toJSON()));
      return this;
    }
  });
  window.NavView = Backbone.View.extend({
    tagName: "li",
    template: _.template($("#navTemplate").html()),
    events:{
      "click a":"onClickNavi"
    },
    initialize: function(){
      _.bindAll(this, "render", "update", "onClickNavi");
      this.model.bind("change", this.render);
      this.model.view = this;
    },
    render: function(){
      $(this.el).html(this.template(this.model.toJSON()));
      return this;
    },
    update: function(title, body){
      this.model.save({title: title, body: body});
    },
    onClickNavi: function(e){
      var id_ = location.hash.replace("#", "");
      this.trigger("showNote", this.model);
    }
  });
  window.AppView = Backbone.View.extend({
    el: "#appView",
    events:{
      "click button": "createNote"
    },
    initialize: function(){
      _.bindAll(this, 'addAll', 'addOne', 'showNote');

      notes.bind("add", this.addOne);
      notes.bind("refresh", this.addAll);
      notes.fetch();
    },
    addAll: function(){
      notes.each(this.addOne);
    },
    addOne: function(note){
      var view = new NavView({model: note});
      view.bind("showNote", this.showNote);
      this.$("ul").append(view.render().el);
    },
    createNote: function(){
      notes.create();
    },
    showNote: function(note){
      this.$("#note").empty();
      var view = new NoteView({model: note});
      console.log(note);
      $("#note").append(view.render().el);
    }
  });

  var app = new AppView;
  
});
